import { asyncRoutes, constantRoutes } from '@/router';

/**
 * Use meta.role to determine if the current user has permission
 * @param adminAuth
 * @param route
 */
function hasPermission(adminAuth, route) {
    if (route.meta && route.meta.authLink) {
        if (route.meta.authSub) {
            // 检查子字段是否有新增或修改权限；不予访问其页面
            return adminAuth.some(auth => route.meta.authLink === auth.authorityUrl && auth[`authority${route.meta.authSub}`] === 1);
        }
        return adminAuth.some(auth => route.meta.authLink === auth.authorityUrl);
    } else {
        return true;
    }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param adminAuth
 */
export function filterAsyncRoutes(routes, adminAuth) {
    const res = [];
    routes.forEach(routeItem => {
        const tmp = { ...routeItem };
        if (hasPermission(adminAuth, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, adminAuth);
            }
            res.push(tmp);
        }
    });

    return res;
}

const state = {
    routes: [],
    addRoutes: []
};

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes;
        state.routes = constantRoutes.concat(routes);
    }
};

const actions = {
    generateRoutes({ commit }, { adminAuth, adminId }) {
        return new Promise(resolve => {
            let accessedRoutes;
            if (adminId === 1) { // 认为1是root
                accessedRoutes = asyncRoutes || [];
            } else {
                accessedRoutes = filterAsyncRoutes(asyncRoutes, adminAuth);
            }
            commit('SET_ROUTES', accessedRoutes);
            resolve(accessedRoutes);
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
